package com.dbq.fast.business.main.model;

import com.dbq.fast.business.main.bean.AdReward;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.common.net.RemoteApiSuccess;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yuanchen on 2018/3/6.
 */

public class RewardModel {

    public static final int RETRY_TIMES = 3;

    private static HttpManager httpManager = HttpManager.getInstance();
    private static AtomicInteger count = new AtomicInteger(0);

    /**
     * 查询奖励情况
     */
    public static void queryReward(RemoteApiSuccess<AdReward> callBack){
        String token = User.getInstance().getToken();
        String account = User.getInstance().getAccount();
        httpManager.getHttpService().queryReward(token, account)
                .compose(new CommonTransformer<>())
                .subscribe(adRewardHttpResult -> {
                    AdReward adReward = adRewardHttpResult.getData();
                    callBack.onSuccess(adReward);
                }, throwable -> {

                });
    }

    /**
     * 上报奖励
     */
    public static void uploadReward(RemoteApiCallBack callBack){
        String token = User.getInstance().getToken();
        String account = User.getInstance().getAccount();
        httpManager.getHttpService().addReward(token, account)
                .compose(new CommonTransformer<>())
                .subscribe(s -> {
                    callBack.onSuccess("");
                }, throwable -> {
                    if(count.get() < RETRY_TIMES){
                        uploadReward(callBack);
                    }else {
                        callBack.onFail(-1, "");
                    }
                    count.getAndIncrement();
                });
    }

}
